package com.yihu.wlyy.job;

import com.yihu.wlyy.entity.WlyyJobConfig;
import com.yihu.wlyy.entity.WlyyQuota;
import com.yihu.wlyy.repository.JobConfigDao;
import com.yihu.wlyy.repository.QuotaDao;
import com.yihu.wlyy.web.quota.WlyyJobConfigVO;
import com.yihu.wlyy.web.quota.WlyyQuotaVO;
import org.quartz.Scheduler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/16.
 * 现在用的数据库保存job不需要用这个类
 */
//@Component
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private QuotaDao quotaDao;
    @Autowired
    private JobConfigDao jobConfigDao;
    private Scheduler scheduler = null;
    @Autowired
    private QuartzHelper quartzHelper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            scheduler = schedulerFactoryBean.getScheduler();
            //查询所有需要开始运行的任务的指标
            List<WlyyJobConfig> jobConfigList=jobConfigDao.findByStatus("1");
            for(WlyyJobConfig wlyyJobConfig:jobConfigList){
                WlyyQuota wlyyQuota=quotaDao.findOne(wlyyJobConfig.getQuotaId());

                WlyyQuotaVO wlyyQuotaVO= new WlyyQuotaVO();
                WlyyJobConfigVO wlyyJobConfigVO=new WlyyJobConfigVO();
                BeanUtils.copyProperties(wlyyQuota,wlyyQuotaVO);
                BeanUtils.copyProperties(wlyyJobConfig,wlyyJobConfigVO);

                Map<String,Object> params=new HashMap<String,Object>();
                params.put("quota",wlyyQuotaVO);
                params.put("jobConfig",wlyyJobConfigVO);
                quartzHelper.addJob(Class.forName(wlyyJobConfig.getJobClass()),wlyyJobConfig.getQuartzCron(),wlyyJobConfig.getId(),params);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
